from typing import List


class Solution:
    def longestWord(self, words: List[str]) -> str:
        words.sort(key=lambda x: (len(x), x))

        visited = set()

        ans = ""
        for word in words:
            if len(word) == 1 or word[:-1] in visited:
                visited.add(word)
                if len(word) > len(ans):
                    ans = word
        return ans


if __name__ == "__main__":
    print(Solution().longestWord(words=["k", "ki", "kir", "kira", "kiran"]))  # "kiran"
    print(Solution().longestWord(words=["a", "banana", "app", "appl", "ap", "apply", "apple"]))  # "apple"
    print(Solution().longestWord(words=["abc", "bc", "ab", "qwe"]))  # ""
